
/*******************************************************************************************************
This dofile replicates the weights analysis in Section 5.2 of <<Difference-in-Differences Estimators of 
Intertemporal Treatment Effects, Clément de Chaisemartin, Xavier D'Haultfœuille, (2024)>>.

The main outputs are: For each periods, the number of weights associated to the parameters of interest, 
\beta_{lp,l}, the number of the negative and positive weights, and their corresponding sums.
********************************************************************************************************/
preserve
*Average treatment since treated
	sort county year
	gen Dgk_temp=0
	forvalue i=1995/2005{
	replace Dgk_temp=inter_bra+Dgk_temp[_n-1] if county==county[_n-1]&year==`i'
	}
	
replace Dgk_temp=Dgk_temp/max(year-year_first_change+1,1)

* Line below necessary because county-level panel is imbalanced
bys state_n year: egen Dgk=max(Dgk_temp)

forvalue i=1/9{
	
*********************************************************************************************************
           di as input _skip(10)  "Year `i': estimated weights associated to beta_{lp, `i'}"
*********************************************************************************************************
	qui {
		
xtset county year
	//Local-projection panel regressions: Y_{g,t−ℓ+1} on group and time fixed effects and Dg,t.
xtreg F`=`i'-1'.Dl_vloans_b yr* inter_bra, fe cluster(state_n)

	//the residual from the regression of Dg,t on group and time fixed effects, in the subsample such that 1 ≤ t ≤ T −ℓ+1.
	areg inter_bra i.year if year<=2005-`i'+1&F`=`i'-1'.Dl_vloans_b!=., absorb(county)
	predict res`i' if year<=2005-`i'+1&F`=`i'-1'.Dl_vloans_b!=.&inter_bra!=., residuals

	//Generating the weights
	
	//i. Numerators
	gen w`i'_lp=Dgk*L`=`i'-1'.res`i' if year>=year_first_change&year>=1994+`i'-1&Dl_vloans_b!=.

	//ii. Denominators
	gen denom_w`i'_temp=inter_bra*res`i' if year>=year_first_change&year<=2005-`i'+1&F`=`i'-1'.Dl_vloans_b!=.
	replace denom_w`i'_temp=0 if denom_w`i'_temp==.
	egen denom_w`i'=total(denom_w`i'_temp)

	//iii. Weights
	replace w`i'_lp=w`i'_lp/denom_w`i' if year>=year_first_change&year>=1994+`i'-1&Dl_vloans_b!=.

	//Positive weights
	gen posW_`i'= w`i'_lp if year>=year_first_change&year>=1994+`i'-1&w`i'_lp>0&Dl_vloans_b!=.&L`=`i'-1'.res`i'!=.

	//Negative weights
	gen negW_`i'= w`i'_lp if year>=year_first_change&year>=1994+`i'-1&w`i'_lp<0&Dl_vloans_b!=.&L`=`i'-1'.res`i'!=.
	}
	
	//The descriptives of the weights
	
tabstat w`i'_lp posW_`i' negW_`i', stats(N sum mean min max sd) columns(statistics)

}
restore	